import { ElMessage } from 'element-plus'
export const url = 'http://192.168.31.6:9003'
// export const url =''
import { ref, watch, onMounted } from 'vue';
export const  timestampToFormat = (timestamp)=> {
  // 创建 Date 对象（时间戳需为毫秒级，示例已满足）
  const date = new Date(timestamp);

  // 提取各时间分量（注意：月份从 0 开始，需 +1）
  const month = date.getMonth() + 1; // 月份（1-12）
  const day = date.getDate(); // 日期（1-31）
  const hours = date.getHours(); // 小时（0-23）
  const minutes = date.getMinutes(); // 分钟（0-59）
  const seconds = date.getSeconds(); // 秒（0-59）

  // 补零函数：将数字转为两位字符串
  function padZero(n) {
    return n.toString().padStart(2, '0');
  }

  // 格式化拼接结果
  return `${padZero(month)}/${padZero(day)} ${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
}
// 复制功能
export const useCopy= async (text)=>{
  try {
    if (navigator.clipboard) {
      await navigator.clipboard.writeText(text);
      ElMessage.success('复制成功!')
      return true;
    } else {
      // 兼容旧版浏览器
      const textarea = document.createElement('textarea');
      textarea.value = text;
      textarea.style.position = 'fixed';
      textarea.style.opacity = '0';
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      ElMessage.success('复制成功!')
      return true;
    }
  } catch (error) {
    ElMessage.error('复制失败!')
    return false;
  }
}
// 数据转换为美国时间
export const convertToUSFormat=(dateStr)=>{
  if (!dateStr) return '';
  // 判断是否已经是美国时间格式
  const usDatePattern = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s(January|February|March|April|May|June|July|August|September|October|November|December)\s\d{1,2},\d{4}$/;
  const usDateTimePattern = /^\d{1,2}:\d{2}(AM|PM),(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s(January|February|March|April|May|June|July|August|September|October|November|December)\s\d{1,2},\d{4}$/;
  
  if (usDatePattern.test(dateStr) || usDateTimePattern.test(dateStr)) {
    return dateStr;
  }
  // 解析日期时间
  const [datePart, timePart] = dateStr.split(' ');
  const [year, month, day] = datePart.split('-');
  
  // 构建Date对象（保持原始时间值）
  const date = new Date(`${year}-${month}-${day}${timePart ? ` ${timePart}` : ''}`);
  
  // 处理data1的格式：Tue July 01,2025
  if (!timePart) {
    const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    const weekday = weekdays[date.getDay()].substring(0, 3); // 取前3个字母
    
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 
                    'July', 'August', 'September', 'October', 'November', 'December'];
    const monthName = months[date.getMonth()];
    
    return `${weekday} ${monthName} ${day},${year}`;
  } 
  // 处理data2的格式：01:59AM,Fri June 20,2025
  else {
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const ampm = hours >= 12 ? 'PM' : 'AM';
    const formattedHours = String(hours % 12 || 12).padStart(2, '0');
    const formattedMinutes = String(minutes).padStart(2, '0');
    
    const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    const weekday = weekdays[date.getDay()];
    
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 
                    'July', 'August', 'September', 'October', 'November', 'December'];
    const monthName = months[date.getMonth()];
    
    return `${formattedHours}:${formattedMinutes}${ampm},${weekday} ${monthName} ${day},${year}`;
  }
}
// 将数据转换为中国时间
export const convertEnglishDateToChinese = (inputStr)=>{
  // 检查是否已经是中国日期格式
  const chineseDateFormat = /^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$/;
  if (chineseDateFormat.test(inputStr)) {
    return inputStr;
  }
  // 定义月份名称映射
  const monthMap = {
    'January': '01', 'February': '02', 'March': '03', 'April': '04', 
    'May': '05', 'June': '06', 'July': '07', 'August': '08', 
    'September': '09', 'October': '10', 'November': '11', 'December': '12'
  };
  
  // 处理包含时间的格式 (例如: '06:38AM,Mon June 23,2025')
  const timePattern = /(\d{2}:\d{2})(AM|PM),([A-Za-z]{3}) ([A-Za-z]+) (\d{1,2}),(\d{4})/;
  const timeMatch = inputStr.match(timePattern);
  
  if (timeMatch) {
    const [, timePart, amPm, , monthName, day, year] = timeMatch;
    const month = monthMap[monthName];
    const formattedDay = day.padStart(2, '0');
    
    // 转换12小时制为24小时制
    let [hours, minutes] = timePart.split(':');
    hours = parseInt(hours, 10);
    
    if (amPm === 'PM' && hours < 12) hours += 12;
    if (amPm === 'AM' && hours === 12) hours = 0;
    
    const formattedHours = hours.toString().padStart(2, '0');
    const seconds = Math.floor(Math.random() * 60).toString().padStart(2, '0');
    
    return `${year}-${month}-${formattedDay} ${formattedHours}:${minutes}:${seconds}`;
  }
  
  // 处理只包含日期的格式 (例如: 'Tue July 01,2025')
  const datePattern = /([A-Za-z]{3}) ([A-Za-z]+) (\d{1,2}),(\d{4})/;
  const dateMatch = inputStr.match(datePattern);
  
  if (dateMatch) {
    const [, , monthName, day, year] = dateMatch;
    const month = monthMap[monthName];
    const formattedDay = day.padStart(2, '0');
    
    return `${year}-${month}-${formattedDay}`;
  }
  
  // 无法识别的格式
  return inputStr;
}
// 判断正负数据
export const isPositive = (priceChangePct)=> {
  return priceChangePct > 0; // 正数返回true，负数和零返回false
}
// 监听storage里面的lang
export const useLocalStorage = (key, defaultValue = '') => {
  const value = ref(localStorage.getItem(key) || defaultValue);

  // 初始化时同步值
  onMounted(() => {
    value.value = localStorage.getItem(key) || defaultValue;
  });

  // 监听 value 变化并更新 localStorage
  watch(value, (newVal) => {
    localStorage.setItem(key, newVal);
  });

  // 监听其他窗口的变化
  const handleStorageChange = (event) => {
    if (event.key === key) {
      value.value = event.newValue || defaultValue;
    }
  };

  onMounted(() => {
    window.addEventListener('storage', handleStorageChange);
  });

  return value;
};